
'''
Implements a single frame of video.
'''

import Image
import time

from gtk.gdk import PixbufLoader
from StringIO import StringIO

class VideoFrame(object):
    '''
    Represents a single frame of video.
    '''
    
    def __init__(self, image, timestamp=time.time()):
        '''
        Initializes a new C{VideoFrame} instance.
        
        @param  image:      The image of the video frame.
        @type   image:      PIL Image
        @param  timestamp:  The timestamp when the frame was grabbed.
        @type   timestamp:  Float
        '''
        self.__image = image
        self.__timestamp = timestamp

#-------------------------------------------------------------------------------
# public properties (read-only)
    @property
    def size(self):
        '''
        The size of the video frame.
        '''
        return self.__image.size
    @property
    def buffer(self):
        '''
        The raw data of the frame as a string.
        '''
        return self.__image.tostring()
    @property
    def image(self): 
        '''
        The PIL Image of the frame.
        '''
        return self.__image
    @property
    def timestamp(self): 
        '''
        The timestamp when the frame was grabbed.
        '''
        return self.__timestamp
    @property
    def pixbuf(self):
        '''
        Get a gtk.gdk.Pixbuf of the video frame.
        '''
        im = self.__image
        file1 = StringIO()  
        im.save(file1, "ppm")  
        contents = file1.getvalue()  
        file1.close()  
        loader = PixbufLoader("pnm")  
        loader.write(contents, len(contents))  
        pixbuf = loader.get_pixbuf()  
        loader.close()  
        return pixbuf
        
    @property
    def jpeg_file(self):
        '''
        Get a file-like object containing JPEG data.
        '''
        file1 = StringIO()
        self.image.save(file1, 'jpeg')
        file1.length = len(file1.getvalue())
        file1.seek(0)
        return file1
